package com.yuma.tingshu.live.api;

import com.alibaba.fastjson.JSON;
import com.yuma.tingshu.common.constant.RedisConstant;
import com.yuma.tingshu.model.live.FromUser;
import com.yuma.tingshu.model.live.SocketMsg;
import com.yuma.tingshu.vo.user.UserInfoVo;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

//@Controller
//@ServerEndpoint("/api/websocket/{roomId}/{token}")
public class WebSocketApiController2 {
    //Cannot invoke "org.springframework.data.redis.core.RedisTemplate.opsForValue()" because "this.redisTemplate" is null
    // WebSocket 服务器端点的管理 和SpringBean的管理机制不完全相同，导致出现了空指针异常

    private static RedisTemplate redisTemplate;

    //@Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        WebSocketApiController2.redisTemplate = redisTemplate;
    }

    @OnOpen
    public void open(Session session, @PathParam("roomId") Long roomId, @PathParam("token") String token) {
        System.out.println("服务器端：直播间" + roomId + "建立了连接");
        //回显一句话：xxx进入直播间
        //1.获取当前用户的昵称
        //UserInfoVo userInfoVo = new UserInfoVo();
        UserInfoVo userInfoVo = (UserInfoVo) this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        //2.创建SocketMsg对象
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMsgContent(userInfoVo.getNickname() + "进入了直播间");
        socketMsg.setMsgType(SocketMsg.MsgTypeEnum.JOIN_CHAT.getCode());
        socketMsg.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        socketMsg.setLiveRoomId(roomId);
        FromUser fromUser = new FromUser();
        fromUser.setAvatarUrl(userInfoVo.getAvatarUrl());
        fromUser.setUserId(userInfoVo.getId());
        fromUser.setNickname(userInfoVo.getNickname());
        socketMsg.setFromUser(fromUser);
        String jsonString = JSON.toJSONString(socketMsg);
        //3.返回消息
        session.getAsyncRemote().sendText(jsonString);
    }

    /*
    {"fromUser":
        {"avatarUrl":"https://pic.rmb.bdstatic.com/bjh/news/0abff0af846626ee3139e852598d3045.png",
        "nickname":"听友10021",
        "userId":29},
      "liveRoomId":"4",
      "msgContent":"1",
      "msgType":"1"}
     */
    @OnMessage
    public void doMessage(Session session, String message, @PathParam("roomId") Long roomId, @PathParam("token") String token) {
        System.out.println("服务器端：" + message);
        //消息返回（1.没有做任何处理，2.返回给发送者自己 3.心跳消息也返回）
        //session.getAsyncRemote().sendText(message);
        //消息返回：1.心跳消息不返回  2.添加时间  3.消息的类型使用枚举表示
        SocketMsg socketMsg = JSON.parseObject(message, SocketMsg.class);
        if (!SocketMsg.MsgTypeEnum.HEART_BEAT.getCode().equals(socketMsg.getMsgType())) {
            socketMsg.setTime(new Date().toLocaleString()); //还可以通过SimpleDateFormat来定义格式
            socketMsg.setMsgType(SocketMsg.MsgTypeEnum.PUBLIC_MSG.getCode());
            String jsonString = JSON.toJSONString(socketMsg);
            session.getAsyncRemote().sendText(jsonString);
        }
    }

    @OnError
    public void doError(Throwable throwable) {
        System.out.println("服务器端：" + throwable.getMessage());

    }

    @OnClose
    public void close(Session session, @PathParam("roomId") Long roomId, @PathParam("token") String token) {
        System.out.println("服务器端：直播间" + roomId + "断开了连接");
        //回显一句话：xxx进入直播间
        //1.获取当前用户的昵称
        //UserInfoVo userInfoVo = new UserInfoVo();
        UserInfoVo userInfoVo = (UserInfoVo) this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        //2.创建SocketMsg对象
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMsgContent(userInfoVo.getNickname() + "退出了直播间");
        socketMsg.setMsgType(SocketMsg.MsgTypeEnum.CLOSE_SOCKET.getCode());
        socketMsg.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        socketMsg.setLiveRoomId(roomId);
        FromUser fromUser = new FromUser();
        fromUser.setAvatarUrl(userInfoVo.getAvatarUrl());
        fromUser.setUserId(userInfoVo.getId());
        fromUser.setNickname(userInfoVo.getNickname());
        socketMsg.setFromUser(fromUser);
        String jsonString = JSON.toJSONString(socketMsg);
        //3.返回消息 !!!!  都已经退出了
        //Message will not be sent because the WebSocket session has been closed
        //解决方案：多人聊天下由其他一个没有关闭的session来发送这个消息给其他没有退出群聊的用户
        //session.getAsyncRemote().sendText(jsonString);
    }
}
